from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from bs4 import BeautifulSoup
import time

def scrape_patient_data(driver_path, visit_number):
    """
    Scrape patient data from the website using the given visit number
    
    Args:
        driver_path (str): Path to the Edge webdriver executable
        visit_number (str): Patient visit number to search for
        
    Returns:
        list: List of dictionaries containing patient information
    """
    try:
        # Initialize the webdriver
        driver = webdriver.Edge(service=Service(driver_path))
        
        # Navigate to the website
        url = 'http://patientview.2m9h.net/Home/Index/MjAyMi8xMC8yMCAwOjAwOjAw'
        driver.get(url)
        
        # Input the visit number
        patient_number_input = driver.find_element(By.ID, 'VisitNumber')
        patient_number_input.send_keys(visit_number)
        
        # Click search button
        search_button = driver.find_element(By.ID, 'search_Btn')
        ActionChains(driver).click(search_button).perform()
        
        # Wait for the content to load
        time.sleep(10)
        
        # Parse the page content
        html = driver.page_source
        soup = BeautifulSoup(html, 'html.parser')
        
        # Find the grid and rows
        grid = soup.find('div', {'class': 'k-grid-content'})
        if not grid:
            return []
            
        rows = grid.find_all('tr')
        patient_records = []
        
        # Extract information from each row
        for row in rows:
            record = row.find_all('td')
            if record:
                patient_info = {
                    'VisitNumberKey': visit_number,
                    'Name': record[11].text.strip(),
                    'Sex': record[13].text.strip(),
                    'Birth': record[14].text.strip(),
                    'Telephone': record[19].text.strip()
                }
                patient_records.append(patient_info)
                
        return patient_records
        
    except Exception as e:
        print(f"Error occurred: {str(e)}")
        return []
        
    finally:
        if 'driver' in locals():
            driver.quit()

def main():
    # Configuration
    driver_path = r'D:\lishaobai\prog\edgedriver_win64\msedgedriver.exe'
    visit_number = "ZA199390"  # You can change this as needed
    
    # Run the scraper
    results = scrape_patient_data(driver_path, visit_number)
    
    # Print results
    for record in results:
        print(f"VisitNumberKey: {record['VisitNumberKey']}, "
              f"Name: {record['Name']}, "
              f"Sex: {record['Sex']}, "
              f"Birth: {record['Birth']}, "
              f"Telephone: {record['Telephone']}")

if __name__ == "__main__":
    main()